# -*- coding: utf-8 -*-
# name: GeometryCalculate.py
# description: 计算要素类的质心X Y值
# 运行之前保证几点:
# 1.本程序先针对个人数据库mdb 或者SDE 进行geometry calculate计算
# 2.指定下面的inSde为源数据库sde文件的路径，outSde为目标数据库的sde文件路径。路径要用 \\ 或者 /。为了避免大家的麻烦，路径和文件名切勿出现中文！！！
# 3.测试在ArcGIS 10.1下可用
# 
import os
import os.path
import time
import string
import arcpy
import arcpy.da

# "Database Connections\Connection to 10.44.47.177.sde"
inSde = "Database Connections\Connection to 10.44.47.177.sde"
outSde = "Database Connections\Connection to 10.44.47.201.sde"
# Set environment settings,for copy feature
arcpy.env.workspace = inSde
# Use ListFeatureClasses to generate a list of shapefiles in the  workspace shown above.
fcList = arcpy.ListFeatureClasses()
# Execute CopyFeatures for each input shapefile
for shapefile in fcList:
    # Determine the new output feature class path and name
    print shapefile
    outFeatureClass = os.path.join(outSde, shapefile)
    print outFeatureClass
    if arcpy.Exists(outFeatureClass):
        arcpy.Delete_management(outFeatureClass)
        print "delete %s success"%shapefile
    arcpy.Copy_management(shapefile, outFeatureClass)
    print(arcpy.GetMessages())
#end copy

# Set environment settings,for calculate feature field
arcpy.env.workspace = outSde

# 先定义一个函数处理要素类的形心点
# ly 图层名称
# TODO:这次偷懒了，所有的featureLayer都是用形心点计算，以后可以改成每种类型一种计算方法
def cal_point(ly):
    print ly
    fieldList = arcpy.ListFields(ly)
    for field in fieldList:
        if(field.name == "x" or field.name == "y"):
            # Execute DeleteField
            arcpy.DeleteField_management(ly, ["x","y"])
            print "%s FeatureLayer's X and Y Field already delete"
            break
    arcpy.AddField_management(ly, "x", "DOUBLE", 9, 6, None,u"点X坐标")
    arcpy.AddField_management(ly, "y", "DOUBLE", 9, 6, None ,u"点y坐标")
    expression1 = "!SHAPE.trueCentroid.X!"
    expression2 = "!SHAPE.trueCentroid.Y!"
    try:
        arcpy.CalculateField_management(ly, "x", expression1,"PYTHON_9.3")
        arcpy.CalculateField_management(ly, "y", expression2,"PYTHON_9.3")
    except Exception as e:
        # 好吧，我偷懒了，这里如果exception抛出，说明SHAPE有None,这应该是一个错误，需要修复，但是我就全给X Y 为0了
        # 之所以采用这样的方式，是为了提高速度，有SHAPE问题的图层采用较慢的方式来计算，没有问题的用快的方式。以后可以采用游标的方式更新。
        print "%s Layer has error shape! don't worry I have another way to fix it!" % ly
        expression1 = "getCentroidX(!SHAPE!)"
        expression2 = "getCentroidY(!SHAPE!,!OBJECTID!)"
        codeblock1 = """def getCentroidX(shape):
            if shape is not None:
                if shape.trueCentroid is not None:
                    return shape.trueCentroid.X
                else:
                    return 0.0
            else:
                return 0.0"""
        codeblock2 = """def getCentroidY(shape,oid):
            if shape is not None:
                if shape.trueCentroid is not None:
                    return shape.trueCentroid.Y
                else:
                    return 0.0
            else:
                return 0.0"""
        arcpy.CalculateField_management(ly, "x",expression1 ,"PYTHON_9.3",codeblock1)
        arcpy.CalculateField_management(ly, "y",expression2 ,"PYTHON_9.3",codeblock2)
    print "%s Layer is complete! have a good day." % ly

# 执行需要的图层
cal_point("FLOODMARK")
cal_point("FZCLK")
cal_point("DANAD")
cal_point("TRANSFER")
cal_point("DIKE")
cal_point("VSECTION")
cal_point("HSECTION")
#完美收官
